package asyncudp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.Timer;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

class TheMomentClient {

    private static final String REMOTE_HOST = "127.0.0.1";
    private static final int REMOTE_PORT = 7686;
    private static final int LOCAL_PORT = 7685;
    private static final EventLoopGroup group = new NioEventLoopGroup();
    private Channel ch;

    TheMomentClient() throws InterruptedException {

        try {

            Bootstrap b = new Bootstrap();

            b.group(group)

             .channel(NioDatagramChannel.class)

             // the udp packet is sending to this address and port
             // .remoteAddress(HOST,PORT)

             .handler(new TheMomentClientHandler());

            // bind(0) means the port is divided by system at random
            ch = b.bind(LOCAL_PORT).sync().channel();

            beats();

        } catch (InterruptedException e) {
            System.err.println("[ERR]: " + e.getMessage());
            close();
        }
    }

    void beats() throws InterruptedException {
        Timer timer = new HashedWheelTimer();
        timer.newTimeout((Timeout timeout) -> {

            ch.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer("[BEAT]", CharsetUtil.UTF_8),
                new InetSocketAddress(REMOTE_HOST, REMOTE_PORT)
            )).sync();

        }, 1, TimeUnit.SECONDS);
    }

    void send(String mes) throws InterruptedException {
        // send the request to port 8080.
        ch.writeAndFlush(new DatagramPacket(
            Unpooled.copiedBuffer("[CLIENT]" + mes, CharsetUtil.UTF_8),
            new InetSocketAddress(REMOTE_HOST, REMOTE_PORT)
        )).sync();
    }

    void close() throws InterruptedException {

        // TheMomentClientHandler will close the DatagramChannel when a
        // response is received.  If the channel is not closed within 5 seconds,
        // print an error message and quit.
        if (!ch.closeFuture().await(5000)) {
            group.shutdownGracefully();
            System.err.println("[LOG]: Request from the server is timed out.");
        }
    }
}